package org.nvframe.entity;

import java.util.ArrayList;

import org.nvframe.component.AbstractComponent;
import org.nvframe.util.Settings;

/**
 * 
 * @author Nik Van Looy
 */
public class EntityImpl implements Entity {

	private String id;
	private int instanceId;
	private boolean enabled;

	private ArrayList<AbstractComponent> components;

	public EntityImpl(String id) {
		this.id = id;
		this.enabled = true;

		components = new ArrayList<AbstractComponent>();
	}
	
	public EntityImpl(String id, Settings settings) {
		this(id);
	}

	/**
	 * add a component to the entity
	 * 
	 * @param component
	 */
	public void addComponent(AbstractComponent component) {
		components.add(component);
	}

	/**
	 * returns the first component found from a given classname
	 * 
	 * @param cls
	 * @return component | null
	 */
	public <D> AbstractComponent getComponent(Class<D> cls) {

		for (AbstractComponent comp : components)
			if (cls.isInstance(comp))
				return comp;

		return null;
	}
	
	/**
	 * returns the first component found from a given id
	 * 
	 * @param id
	 * @return component | null
	 */
	public <D> AbstractComponent getComponent(String id) {
		if(components.size() == 0)
			return null;
		
		for (AbstractComponent comp : components)
			if (comp.getId().equals(id))
				return comp;

		return null;
	}

	/**
	 * check if an entity instance contains a component of a given class
	 * 
	 * @param cls
	 * @return true if componentclass exists in map
	 */
	public boolean hasComponent(Class<?> cls) {
		if(components.size() == 0)
			return false;
		
		for (AbstractComponent comp : components)
			if (cls.isInstance(comp))
				return true;
		
		return false;
	}
	
	/**
	 * return the component count
	 * 
	 * @return Number of components
	 */
	public int getComponentCount() {
		return components.size();
	}

	/**
	 * print al the components
	 * 
	 * note: currently only for debug purposes
	 */
	public void printAllComponents() {
		for (AbstractComponent component : components) {
			System.out.println(component.getId());
		}
	}

	/**
	 * notifies all the components this entity is removed
	 * 
	 * note: the entity is not removed, it's only "deactivated"
	 */
	public void removed() {
		for (AbstractComponent component : components) {
			component.removed(this);
		}
		
		this.enabled = false;
	}
	
	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public String getId() {
		return id;
	}

	public int getInstanceId() {
		return instanceId;
	}

	public void setInstanceId(int instanceId) {
		this.instanceId = instanceId;
	}
}